//
//  ReturnListViewController.m
//  TengyunStation
//
//  Created by Johnny on 15/9/1.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "ReturnListViewController.h"
#import "SocketRequest.h"
#import "ReturnExpressCell.h"
#import "Singleton.h"

@interface ReturnListViewController ()<SocketRequestDelegate> {
    SocketRequest *_socketRequest;
    int _positionPage;
}

@end

@implementation ReturnListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"已退件快递";
        _socketRequest = [[SocketRequest alloc] initWithSocketRequestDelegate:self];
        _positionPage = 1;
        _returnList = [NSMutableArray arrayWithCapacity:1];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.    
    [self getReturnListFromSqlit];
    [self handelNetWorkMethod];
}

- (void)getReturnListFromSqlit {
    NSString *sql = [NSString stringWithFormat:@"ORDER BY retreatTime DESC"];
    NSArray *array = [ReturnExpress findByCriteria:sql];
    [_returnList addObjectsFromArray:array];
    [self.tableView reloadData];
    if (_returnList.count > 0) {
        [ToastActivity makeActivity:@"加载中..." InView:self.view];
    }
    [self getReturnListSocket];
}

- (void)getReturnListSocket {
    if (_returnList.count <= 0) {
        [self.tableView makeLoading];
    } else {
        self.tableView.backgroundView = nil;
    }
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STR6"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    NSString *page = [NSString stringWithFormat:@"%d",_positionPage];
    [mutableData appendBytes:[page UTF8String] length:16];
    [mutableData appendBytes:[@"10" UTF8String] length:16];
    [_socketRequest addSocketData:mutableData SocketTag:1];
}

#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _returnList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_returnList.count == (indexPath.row + 1)) {
        return 240;
    }
    return 250;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIndentifier = @"ReturnExpressCell";
    ReturnExpressCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"ReturnExpressCell" owner:self options:nil] lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    ReturnExpress *express = [_returnList objectAtIndex:indexPath.row];
    [cell reloadReturnExpressCell:express];
    return cell;
}

#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.tableView pullScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self.tableView pullscrollViewDidEndDragging:scrollView];
}

#pragma mark PullTableViewDelegate
- (void)startRefreshHeaderView {
    _positionPage = 1;
    [self getReturnListSocket];
}

- (void)startRefreshFooterView {
    _positionPage += 10;
    [self getReturnListSocket];
}

#pragma mark SocketRequestDelegate
- (void)socket:(GCDAsyncSocket *)socket Code:(NSString *)code Msg:(NSString *)msg Data:(NSData *)data {
    [self.tableView endRefreshPullTableView];
    [ToastActivity dismissInView:self.view];
    if ([code isEqualToString:SuccessSocket]) {
        if (_positionPage == 1) {
            [_returnList removeAllObjects];
        }
        NSString *content = [SocketMethod stringDecryHexData:data];
        DLog(@"%@",content);
        NSArray *array = [content componentsSeparatedByString:@"|"];
        NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:1];
        for (NSString *string in array) {
            if (string.length > 0) {
                ReturnExpress *express = [[ReturnExpress alloc] initWithString:string];
                [express saveOrUpdate];
                [mutableArray addObject:express];
            }
        }
        [_returnList addObjectsFromArray:mutableArray];
        self.tableView.isShowFooterView = ((mutableArray.count < 10) ? NO : YES);
        if (_returnList.count <= 0) {
            [self.tableView makeTip:@"无已退件快递"];
        } else {
            self.tableView.backgroundView = nil;
        }
        [self.tableView reloadData];
    } else {
        if (_returnList.count <= 0) {
            [self.tableView makeTip:msg];
        } else {
            [DSToast showText:msg InView:self.view];
        }
    }
}

- (void)socket:(GCDAsyncSocket *)socket Msg:(NSString *)msg {
    [self.tableView endRefreshPullTableView];
    [ToastActivity dismissInView:self.view];
    if (_returnList.count <= 0) {
        [self.tableView makeTip:msg Title:@"重新加载" Target:self Selector:@selector(getReturnListSocket)];
    }
    [DSToast showText:msg InView:self.view];
}

- (void)dealloc {
    _socketRequest = nil;
    _returnList = nil;
}

@end
